<template>
  <div class="item-one">
    <div class="title">
      <span>分账查询</span>
      <span :key="key"></span>
      <div>
        <!-- <el-button type="primary" disabled>同步银行订单</el-button> -->
        <el-button type="primary" :disabled="imp" @click="joinexportlist()"
          >导出任务列表</el-button
        >
        <el-button type="primary" :disabled="imp" @click="merchantexcel()"
          ><i class="el-icon-download"></i>申请导出</el-button
        >
        <el-button
          icon="el-icon-refresh"
          @click.native="updateClick()"
        ></el-button>
      </div>
    </div>
    <div class="container">
      <div class="screeningBox">
        <div class="leftBox">
          <div
            class="leftitem"
            v-if="
              userInfo.rolesId != 5 &&
              userInfo.rolesId != 6 &&
              userInfo.rolesId != 4
            "
          >
            <el-form ref="newObj" :model="newObj">
              <el-autocomplete
                v-if="
                  userInfo.rolesId == 1 ||
                  userInfo.rolesId == 8 ||
                  userInfo.rolesId == 9
                "
                class="service"
                placeholder="请选择一级服务商"
                v-model.trim="newObj.agent1"
                :fetch-suggestions="querySearch"
                @select="serviceid"
              ></el-autocomplete>
              <el-autocomplete
                v-if="
                  userInfo.rolesId == 1 ||
                  userInfo.rolesId == 8 ||
                  userInfo.rolesId == 2 ||
                  userInfo.rolesId == 9
                "
                class="service"
                placeholder="请选择二级服务商"
                v-model.trim="newObj.agent2"
                :fetch-suggestions="querySearch2"
                @select="serviceid2"
              ></el-autocomplete>
              <el-autocomplete
                v-if="
                  userInfo.rolesId != 4 &&
                  userInfo.rolesId != 5 &&
                  userInfo.rolesId != 6
                "
                class="service"
                placeholder="业务经理"
                v-model.trim="newObj.bd"
                :fetch-suggestions="BDname"
                @select="BDid"
              ></el-autocomplete>
            </el-form>
          </div>
          <div class="leftitem">
            <el-form label-width="80px">
              <el-input
                class="merchants width60"
                placeholder="订单号"
                style="width: 48%"
                v-model="newObj.tradeNo"
              ></el-input>
            </el-form>
          </div>
          <div class="leftitem">
            <el-date-picker
              v-model="date"
              type="datetimerange"
              :picker-options="pickerOptions"
              value-format="yyyy-MM-dd HH:mm:ss"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              :clearable="false"
              :default-time="['00:00:00', '23:59:59']"
            >
            </el-date-picker>
          </div>
        </div>
        <div class="rightBox">
          <div
            class="rightitem"
            v-if="userInfo.rolesId != 5 && userInfo.rolesId != 6"
          >
            <el-form ref="newObj" label-width="80px" :model="newObj">
              <el-input
                class="width60"
                placeholder="商户号"
                v-model="newObj.merchantNo1"
              ></el-input>
              <el-autocomplete
                class="width60"
                :debounce="300"
                placeholder="商户名"
                v-model.trim="newObj.merchantName1"
                :trigger-on-focus="false"
                :fetch-suggestions="querySearchMerchant"
                @select="okmerchants"
              ></el-autocomplete>
            </el-form>
          </div>
          <div class="rightitem" v-if="userInfo.rolesId != 6">
            <el-form label-width="80px" ref="newObj" :model="newObj">
              <el-autocomplete
                class="width60"
                placeholder="门店名"
                v-model="newObj.shopName"
                :trigger-on-focus="false"
                :fetch-suggestions="querySearchShopName"
                @select="okshop"
              ></el-autocomplete>
              <el-input
                class="width60"
                placeholder="分账通道商户号"
                v-model="newObj.splitMerNo"
              ></el-input>
            </el-form>
          </div>
          <div class="rightitem">
            <el-button
              icon="el-icon-search"
              type="primary"
              :disabled="searchBtn"
              @click="search"
              >搜索</el-button
            >
            <el-button icon="el-icon-refresh" type="primary" @click="reset"
              >重置</el-button
            >
          </div>
        </div>
      </div>
      <!-- 表格 -->
      <div class="tableBox">
        <el-table
          ref="multipleTable"
          :data="tradesList"
          tooltip-effect="dark"
          style="width: 100%"
          stripe
          :header-cell-style="tableHeaderColor"
          v-loading="loading"
        >
          <el-table-column type="selection" width="55"></el-table-column>
          <el-table-column
            align="center"
            :index="indexMethod"
            type="index"
            label="序号"
          ></el-table-column>
          <el-table-column
            prop="settleTime, tradeNo"
            align="center"
            width="240"
            label="交易时间?交易订单号"
            :render-header="renderheader"
          >
            <template slot-scope="scope">
              <div>{{ scope.row.settleTime }}</div>
              <div>{{ scope.row.tradeNo }}</div>
            </template>
          </el-table-column>
          <el-table-column
            prop="tradeMerName, tradeMerNo"
            label="交易商户名称?交易商户号"
            align="center"
            :render-header="renderheader"
          >
            <!-- tradeMerName -->
            <template slot-scope="scope">
              <div>{{ scope.row.tradeMerName }}</div>
              <div>{{ scope.row.tradeMerNo }}</div>
            </template>
          </el-table-column>
          <el-table-column
            prop="splitMerName, splitMerNo"
            label="分账商户名称?分账通道商户号"
            align="center"
            :render-header="renderheader"
          >
            <!-- splitMerName -->
            <template slot-scope="scope">
              <div>{{ scope.row.splitMerName }}</div>
              <div>{{ scope.row.splitMerNo }}</div>
            </template>
          </el-table-column>
          <el-table-column
            prop="totalFee"
            align="center"
            label="交易金额"
          ></el-table-column>
          <el-table-column
            prop="bearFee"
            align="center"
            label="交易手续费"
          ></el-table-column>
          <el-table-column prop="splitFee" label="分账金额" align="center">
            <template> </template>
          </el-table-column>
          <!-- 同步分账、异步分账 -->
          <el-table-column
            prop="splitType"
            label="分账类型"
            align="center"
            :render-header="renderheader"
          >
            <template slot-scope="scope">
              <div>
                {{ scope.row.splitType === 1 ? "同步分账" : "异步分账" }}
              </div>
            </template>
          </el-table-column>
          <el-table-column
            prop="feeFlag"
            align="center"
            label="是否手续费承担方"
          >
            <template slot-scope="scope">
              <div>{{ scope.row.feeFlag === "Y" ? "是" : "否" }}</div>
            </template>
          </el-table-column>
          <el-table-column
            fixed="right"
            align="center"
            label="操作"
            width="120"
            style="display: flex"
          >
            <template slot-scope="scope">
              <div>
                <el-button
                  type="text"
                  size="small"
                  @click="orderDetail(scope.row.id, scope.row.tradeId)"
                  >订单详情</el-button
                >
              </div>
              <el-button
                type="text"
                size="small"
                @click="tradeDetail(scope.row.id)"
                >分账详情</el-button
              >
              <!-- <div v-if="scope.row.payStatusCode == 1"> -->
              <!-- <el-button type="text" size="small" v-if="myrolesId == 1 || myrolesId ==2 || myrolesId == 8 || myrolesId == 5 || myrolesId == 6" @click="refund(scope.row.totalFee,scope.row.id)">退款</el-button> -->
              <!-- </div> -->
            </template>
          </el-table-column>
        </el-table>
        <div class="pagination">
          <el-pagination
            background
            @current-change="handleCurrentChange"
            @size-change="sizechange"
            :page-size="obj.page"
            :current-page.sync="obj.size"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
          ></el-pagination>
        </div>

      </div>
    </div>
  </div>
</template>

<script>
import {
  getSplitList,
  getTradeDetail,
  getservice,
  getBD,
  merchantlist,
  shop,
  exportExcels,
  queryorder,
} from "@/api/api";
import md5 from "js-md5";
export default {
  name: "item-one",

  data() {
    return {
      key: 0,
      userInfo: "",
      date: "",
      loading: false,
      total: 0,
      tradesInfo: {
        tradeMerId: "",
        tradeNo: "",
        splitMerNo: "",
      },
      newObj: {
        tradeMerId: "",
        tradeNo: "",
        splitMerNo: "",
      },
      agentArr1: [],
      agentArr2: [],
      serviceArr1: [],
      serviceArr2: [],
      bdArr: [],
      merchantNameList: [],
      shopLists: [],
      searchBtn: false,
      page: 1,
      size: 10,
      obj: {},
      imp: false,
      tradesList: [],
      pickerOptions: {
        // 设置不能超过未来时间
        // disabledDate: (time) => {
        //   // 设置可选择的日期为今天之后的一个月内
        //   const curDate = (new Date()).getTime()
        //   // 这里算出一个月的毫秒数,这里使用30的平均值,实际中应根据具体的每个月有多少天计算
        //   const day = 31 * 24 * 3600 * 1000
        //   const dateRegion = curDate - day
        //   return time.getTime() > Date.now() - 8.64e7 ||
        //   time.getTime() < dateRegion
        // }
        // 设置不能超过当天的23:59:59
        disabledDate(time) {
          let nowDate = new Date();
          let date = {
            year: nowDate.getFullYear(),
            month: nowDate.getMonth() + 1,
            date: nowDate.getDate(),
          };
          let timeDate =
            date.year + "-" + date.month + "-" + date.date + " 23:59:59";
          let times = new Date(timeDate).getTime();
          return time.getTime() > times;
        },
      },
    };
  },
  created() {
    this.userInfo = JSON.parse(sessionStorage.getItem("userInfo"));
    const start = new Date();
    start.setTime(start.getTime());
    const year = start.getFullYear();
    let month = start.getMonth() + 1;
    if (month < 10) {
      month = "0" + month;
    }
    let date = start.getDate();
    if (date < 10) {
      date = "0" + date;
    }
    const date1 = year + "-" + month + "-" + date + " 00:00:00";
    const date2 = year + "-" + month + "-" + date + " 23:59:59";
    this.date = [date1, date2];
    this.getSplitList1();
  },

  methods: {
    //修改thead 背景色
    tableHeaderColor({ row, column, rowIndex, columnIndex }) {
      if (rowIndex === 0) {
        return "background-color: #F0F0F0;font-weight: 500;font-size:14px;color:#000;";
      }
    },
    // 分页导航
    handleCurrentChange(val) {
      this.page = val;
      this.getSplitList1();
      this.$nextTick(() => {
        document.querySelectorAll(".content")[0].scrollTop = "0";
      });
    },
    // 分页数量
    sizechange(val) {
      this.page = 1;
      this.size = val;
      this.getSplitList1();
      this.$nextTick(() => {
        document.querySelectorAll(".content")[0].scrollTop = "0";
      });
    },
    // 刷新
    updateClick() {
      this.$forceUpdate();
    },
    renderheader(h, { column, $index }) {
      return h("span", {}, [
        h("span", {}, column.label.split("?")[0]),
        h("br"),
        h("span", {}, column.label.split("?")[1]),
      ]);
    },
    // 分页序号
    indexMethod(index) {
      return (this.page - 1) * this.size + index + 1;
    },
    // 获取分账列表
    async getSplitList1() {
      let list = {};
      list = {
        agent1Id: this.tradesInfo.agent1Id,
        agent2Id: this.tradesInfo.agent2Id,
        bdid: this.tradesInfo.BDname,
        channelid: "",
        finishTime: this.date[1],
        shopId: this.tradesInfo.shopId,
        splitMerNo: this.tradesInfo.splitMerNo,
        splitType: "",
        startTime: this.date[0],
        splitMerId: this.tradesInfo.merchantName,
        tradeNo: this.tradesInfo.tradeNo,
        tradeMerNo: this.tradesInfo.merchantNo1,
        page: this.page,
        size: this.size,
      };
      var day;
      var sdate = new Date(this.date[0]);
      var edate = new Date(this.date[1]);
      day = edate.getTime() - sdate.getTime();
      day = parseInt(day / (1000 * 60 * 60 * 24));
      if (day >= 31) {
        this.$message.error("只能查询一个月内的交易");
        this.searchBtn = false;
      } else {
        this.loading = true;
        const res = await getSplitList(list);
        if(res.code == 405) {
          sessionStorage.removeItem('token')
          this.$router.push('/login')
        } else {
          if (res.code !== 200) {
            this.$message.error(res.message);
            this.loading = false;
            this.searchBtn = false;
            this.tradesInfo = {};
            this.newObj = {};
          } else {
            this.searchBtn = false;
            this.page = res.data.current;
            this.size = res.data.size;
            this.total = res.data.total;
            this.tradesList = res.data.records;
            this.loading = false;
          }
        }
      }
    },
    createFilter(queryString) {
      return (restaurant) => {
        return (
          restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) !==
          -1
        );
      };
    },
    BDname(queryString, cb) {
      let bdArr = this.bdArr;
      let results = queryString
        ? bdArr.filter(this.createFilter(queryString))
        : bdArr;
      // 调用 callback 返回建议列表的数据
      cb(results);
    },
    BDid(item) {
      this.newObj.BDname = item.id;
    },
    // 一级服务商查询
    async serviceid(item) {
      this.serviceArr1 = [];
      const res = await getservice({
        type: 2,
        parentid: item.id,
      });
      if(res.code == 405) {
        sessionStorage.removeItem('token')
        this.$router.push('/login')
      } else {
        res.data.rows.forEach((val) => {
          this.serviceArr1.push({ value: val.agentname, id: val.id });
        });
        this.newObj.agent1Id = item.id;
      }
    },
    //  一级服务商获取
    async querySearch(val, cb) {
      let sosolist = {};
      sosolist = {
        page: 1,
        size: 10,
        type: 1,
        keywords: this.newObj.agent1,
      };
      const res = await getservice(sosolist);
      if (res.code == 405) {
        sessionStorage.removeItem("token");
        this.$router.push("/login");
      } else {
        this.agentArr1 = [];
        res.data.rows.forEach((value) => {
          this.agentArr1.push({ value: value.agentname, id: value.id });
        });
        let results = val
          ? this.agentArr1.filter(this.createFilter(val))
          : this.agentArr1;
        cb(results);
      }
    },
    // 二级服务商查询
    serviceid2(item) {
      this.newObj.agent2Id = item.id;
      this.newObj.BDname = "";
      this.getBD(item.id);
    },
    async getBD(id) {
      this.bdArr = [];
      const res = await getBD({
        agentid: id,
      });
      for (var i = 0; i < res.data.rows.length; i++) {
        this.bdArr.push({
          value: res.data.rows[i].name,
          id: res.data.rows[i].id,
        });
      }
    },
    // 二级服务商获取
    async querySearch2(val, cb) {
      let servicearr = this.serviceArr1;
      let sosolist = {};
      sosolist = {
        page: 1,
        size: 10,
        type: 2,
        keywords: this.newObj.agent2,
      };
      const res = await getservice(sosolist);
      if (res.code === 405) {
        sessionStorage.removeItem("token");
        this.$router.push("/login");
      } else {
        this.agentArr2 = [];
        res.data.rows.forEach((value) => {
          this.agentArr2.push({ value: value.agentname, id: value.id });
        });
        let results = val
          ? this.agentArr2.filter(this.createFilter(val))
          : this.agentArr2;
        // 调用 callback 返回建议列表的数据
        cb(results);
      }
    },
    // 商户名获取
    async querySearchMerchant(val, cb) {
      let sosolist = {};
      sosolist = {
        page: 1,
        size: 10,
        bdId: this.newObj.BDname,
        agent1Id: this.newObj.agent1Id,
        agent2Id: this.newObj.agent2Id,
        merchantName: this.newObj.merchantName1,
      };
      const res = await merchantlist(sosolist);
      if (res.code === 405) {
        sessionStorage.removeItem("token");
        this.$router.push("/login");
      } else {
        this.merchantNameList = [];
        res.data.forEach((value) => {
          this.merchantNameList.push({
            value: value.merchantName,
            id: value.id,
          });
        });
        let servicearr = this.merchantNameList;
        let results = val
          ? servicearr.filter(this.createFilter(val))
          : servicearr;
        // 调用 callback 返回建议列表的数据
        cb(results);
      }
    },
    okmerchants(val) {
      this.newObj.merchantName = val.id;
    },
    // 门店名获取
    async querySearchShopName(val, cb) {
      const res = await shop({
        page: 1,
        size: 10,
        merchantId: this.newObj.merchantName,
        keywords: this.newObj.shopName,
      });
      if (res.code == 405) {
        sessionStorage.removeItem("token");
        this.$router.push("/login");
      } else {
        this.shopLists = [];
        res.data.forEach((value) => {
          this.shopLists.push({ value: value.shopName, id: value.id });
        });
        let results = val
          ? this.shopLists.filter(this.createFilter(val))
          : this.shopLists;
        // 调用 callback 返回建议列表的数据
        cb(results);
      }
    },
    // 选择门店
    okshop(val) {
      this.newObj.shopId = val.id;
      this.newObj.shopName = val.value;
    },
    // 重置
    reset() {
      const start = new Date();
      start.setTime(start.getTime());
      const year = start.getFullYear();
      let month = start.getMonth() + 1;
      if (month < 10) {
        month = "0" + month;
      }
      let date = start.getDate();
      if (date < 10) {
        date = "0" + date;
      }
      const date1 = year + "-" + month + "-" + date + " 00:00:00";
      const date2 = year + "-" + month + "-" + date + " 23:59:59";
      this.date = [date1, date2];
      this.newObj = {};
      this.tradesInfo = {};
      this.page = 1;
    },
    // 搜索
    search() {
      this.page = 1;
      this.searchBtn = true;
      if (!this.newObj.agent1) {
        this.newObj.agent1Id = "";
      }
      if (!this.newObj.agent2) {
        this.newObj.agent2Id = "";
      }
      if (!this.newObj.bd) {
        this.newObj.BDname = "";
      }
      if (!this.newObj.tradeNo) {
        this.newObj.tradeNo = "";
      }
      if (!this.newObj.merchantNo1) [(this.newObj.merchantNo = "")];
      if (!this.newObj.merchantName1) {
        this.newObj.merchantName = "";
      }
      if (!this.newObj.shopName) {
        this.newObj.shopId = "";
      }
      this.tradesInfo = { ...this.newObj };
      this.getSplitList1();
      this.tradesInfo = {
        tradeMerId: "",
        tradeNo: "",
        splitMerNo: "",
      };
    },
    // 跳转导出
    joinexportlist() {
      this.$router.push({
        path: "/exportlist",
        query: {
          type: "trade",
          exportType: 5
        },
      });
      sessionStorage.setItem('exportType', '5')
    },
    // 导出
    merchantexcel() {
      this.imp = true;
      const loading = this.$loading({
        lock: true,
        text: "导出操作可能耗时较长，请耐心等待",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)",
      });
      let sosolist = {};
      sosolist = {
        page: this.page,
        size: this.size,
        agent1Id: this.tradesInfo.agent1Id,
        agent2Id: this.tradesInfo.agent2Id,
        startTime: this.date[0],
        finishTime: this.date[1],
        merchantId: this.tradesInfo.merchantId,
        shopId: this.tradesInfo.shopId,
        exportType: 5,
      };
      Object.assign(sosolist, this.tradesInfo);
      exportExcels(sosolist).then((res) => {
        if (res.data.code == 405) {
          sessionStorage.removeItem("token");
          this.$router.push("/login");
          loading.close();
          this.exxxx = false;
        } else if (res.data.code == 200) {
          this.$message({
            message: "导出申请成功，请到导出任务列表中下载",
            type: "success",
          });
          loading.close();
          this.exxxx = false;
          this.imp = false;
        } else {
          this.$message.error(res.data.message);
          loading.close();
          this.exxxx = false;
          this.imp = false;
        }
      });
    },
    // 分账详情
    async tradeDetail(id) {
      const res = await getTradeDetail(id);
      this.$router.push({
        path: "/tradedetail",
        query: {
          id,
        },
      });
    },
    // 订单详情
    async orderDetail(val, code) {
      if (val == 2 || val == 3 || val == 4 || val == 6 || val == 8) {
        await queryorder({}, code);
      }
      this.$router.push({
        path: "/indentdetails",
        query: {
          no: code,
        },
      });
    },
  },
};
</script>

<style scoped>
.title {
  background: #fff;
  padding: 10px 10px;
  font-size: 18px;
  font-weight: 500;
  display: flex;
  justify-content: space-between;
}
.name {
  width: 25%;
}
.screeningBox {
  width: 100%;
  display: flex;
}
.leftBox,
.rightBox {
  width: 50%;
  padding: 0 15px;
  box-sizing: border-box;
}
.leftBox > .leftitem {
  margin-bottom: 15px;
}
.rightBox > .rightitem {
  margin-bottom: 15px;
}
.merchants {
  width: 50%;
}
.tableBox {
  margin-top: 20px;
}
.servicename {
  width: 60%;
}
.servicelevel {
  width: 20%;
}
.width20 {
  width: 20%;
}
.width30 {
  width: 30%;
}
.red {
  color: #f9607d;
}
.stitle {
  padding: 5px 0;
  font-size: 18px;
}
.statistical {
  width: 100%;
  display: flex;
  justify-content: space-around;
  align-items: center;
  background: #00152a;
  color: #fff;
  padding: 12px;
  box-sizing: border-box;
}
.statistical > .statisticalitem {
  text-align: center;
  line-height: 200%;
}
.BDname {
  width: 20%;
}
.width60 {
  width: 40%;
}
.yuan {
  color: #c1c5cb;
  font-size: 12px;
  position: relative;
  left: -20px;
}
.green {
  background: #97c05c;
  color: #fff;
  padding: 0 5px;
  border-radius: 10px;
}
.orange {
  background: #f29c38;
  color: #fff;
  padding: 0 5px;
  border-radius: 10px;
}
.hui {
  background: #888888;
  color: #fff;
  padding: 0 5px;
  border-radius: 10px;
}
.reds {
  background: #d3362f;
  color: #fff;
  padding: 0 5px;
  border-radius: 10px;
}
.blue {
  background: #4154af !important;
  color: #fff;
  padding: 0 5px;
  border-radius: 10px;
}
.notice-tip {
  color: red;
  font-size: 8px;
  text-align: center;
}
</style>